import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoServer {
    ServerSocket serverSocket = null;
    ExecutorService service = Executors.newCachedThreadPool();

    //指定服务器端的port
    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    //启动服务器
    public void start() throws IOException {
        System.out.println("服务器启动!");
        //服务器往往是7*24小时一直运转~
        while(true){
            //获取一个和服务器端的连接
            //Socket socket = serverSocket.accept();
            //处理连接
            //processConnection(socket);
            Socket socket = serverSocket.accept();
            service.submit(new Runnable() {
                @Override
                public void run() {
                    processConnection(socket);
                }
            });
        }
    }
    public void processConnection(Socket socket){
        System.out.printf("[%s:%d] 客户端已经上线~\n", socket.getInetAddress().toString(), socket.getPort());
        //与udp同理三部曲，不过tcp是字节流，使用流对象来读请求和发响应
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
            //为了方便，使用Scanner直接当做字符来处理
            Scanner scanner = new Scanner(inputStream);
            //客户端可能会多次发请求
            while(true){
                if(!scanner.hasNext()){
                    System.out.printf("[%s:%d] 客户端已经下线~\n", socket.getInetAddress().toString(), socket.getPort());
                    break;
                }
                //1、读取请求并解析
                String request = scanner.next();
                //2.根据请求计算响应
                String response = process(request);
                //3.将响应发送给客户端
                PrintWriter writer = new PrintWriter(outputStream);
                writer.println(response);
                //刷新缓冲区
                writer.flush();
                //打印日志
                System.out.printf("[%s:%d] req: %s, resp: %s\n", socket.getInetAddress().toString(), socket.getPort(), request, response);

            }
        } catch (IOException e){
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public String process(String request){
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer server = new TcpEchoServer(8080);
        server.start();
    }
}
